package one.stand.controller;

import com.google.common.collect.Lists;
import com.jmp.api.dto.UsersAuthListRequest;
import com.jmp.api.dto.UsersAuthListResponse;
import com.jmp.api.dto.UsersAuthRequest;
import com.jmp.api.dto.UsersResponse;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.CardListDto;
import com.jmp.base.dto.CardListVo;
import com.jmp.feign.CardFeign;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.*;
import one.stand.model.ResultModel;
import one.stand.service.user.MenuService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author cjr
 */
@RequestMapping("/users")
@RestController
public class UsersController {

    @Autowired
    private CardFeign cardFeign;

    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private MenuService menuService;

    @PostMapping("")
    @ApiOperation(value = "员工列表(分页)")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<UsersResponse> index(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        CardListDto cardListDto = CardListDto.builder()
                .companyId(optUser.getCompanyId())
                .status(1)
                .build();
        cardListDto.setPageNum(request.getPageNum());
        cardListDto.setPageSize(request.getPageSize());
        ResultModel<CardListVo> cardListVoResultModel = cardFeign.list(cardListDto);
        AssertUtil.isTrue(cardListVoResultModel);
        PageResponse2<UsersResponse.User> users = ConvertUtils.page2(cardListVoResultModel.getData().getCardPage(), card -> {
            UserDto user = userAdminService.get(card.getUserId());
            return UsersResponse.User.builder()
                    .userId(user.getUserId())
                    .userImg(user.getUserImg())
                    .userName(user.getName())
                    .admin(optUser.getCompanyId().equals(user.getRoleId()))
                    .build();
        });
        UsersResponse response = UsersResponse.builder()
                .users(users)
                .build();
        return ResultModel.success(response);
    }

    @PostMapping("/auth/list")
    @ApiOperation(value = "员工权限列表")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<UsersAuthListResponse> authList(@RequestAttribute UsersAuthListRequest request) {
        List<MenuTreeDto> menuTreeDtos = menuService.getAll(null, MenuService.TYPE_CRM_APP);
        List<Integer> menuOpen = menuService.getOpen(request.getUserId());
        List<UsersAuthListResponse.Auth> auths = ConvertUtils.list(menuTreeDtos, menuTreeDto -> {
            boolean isOpen = true;
            List<UsersAuthListResponse.Auth> childList = null;
            if (OneListUtil.isNotEmpty(menuTreeDto.getMenus())) {
                childList = Lists.newArrayList();
                boolean isOpenChild = true;
                for (MenuTreeDto childDto : menuTreeDto.getMenus()) {
                    isOpenChild = menuOpen.contains(childDto.getMenu().getMenuId());
                    if (isOpen) {
                        isOpen = isOpenChild;
                    }
                    childList.add(UsersAuthListResponse.Auth.builder()
                            .authId(childDto.getMenu().getMenuId())
                            .authName(childDto.getMenu().getValue())
                            .authIcon(childDto.getMenu().getIcon())
                            .open(isOpenChild ? 1 : 0)
                            .build());
                }
            }
            return UsersAuthListResponse.Auth.builder()
                    .authId(menuTreeDto.getMenu().getMenuId())
                    .authName(menuTreeDto.getMenu().getValue())
                    .authIcon(menuTreeDto.getMenu().getIcon())
                    .open(isOpen ? 1 : 0)
                    .authList(childList)
                    .build();
        });

        UsersAuthListResponse response = UsersAuthListResponse.builder()
                .auths(auths)
                .build();
        return ResultModel.success(response);
    }

    @PostMapping("/auth")
    @ApiOperation(value = "员工权限修改")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel auth(@RequestAttribute UsersAuthRequest request) {
        UserDto user = userAdminService.get(request.getUserId());
        AssertUtil.isFalse(user.isBoss(), "不能编辑管理员权限");

        menuService.update(request.getUserId(), request.getAuthIds(), request.getOpen() == 1);
        return ResultModel.success();
    }
}
